from django.views import View
from django.shortcuts import render
from django.db.models import Count
from django.http import JsonResponse
import collections
from web import models
class DashboardView(View):
    '''
    问题概览视图处理  dashboard
    '''
    def get(self,request,project_id):
        #有序字典
        status_dict=collections.OrderedDict()
        for key,text in models.Issues.status_choices:
            status_dict[key]={'text':text,'count':0}
        issues_data=models.Issues.objects.filter(project_id=project_id).values('status').annotate(ct=Count('id'))
        for item in issues_data:
            status_dict[item['status']]['count']=item['ct']
        #项目成员
        user_list=models.ProjectUser.objects.filter(project_id=project_id).values('user_id','user__username')
        #最近的10个问题
        top_ten=models.Issues.objects.filter(project_id=project_id).order_by('-id')[0:10]
        context={
            'status_dict':status_dict,
            'user_list':user_list,
            'top_ten_object':top_ten
        }
        return render(request,'web/dashboard.html',context)

class IssuesChartView(View):
    '''
    在概览页面中生成highcharts 所需要的数据
    '''
    def get(self,request,project_id):
        import datetime
        import time
        today=datetime.datetime.now()
        data_dict=collections.OrderedDict()
        for i in range(0,30):
            date=today-datetime.timedelta(days=i)
            data_dict[date.strftime('%Y-%m-%d')]=[time.mktime(date.timetuple())*1000,0]
        result=models.Issues.objects.filter(project_id=project_id,create_datetime__gte=today-datetime.timedelta(days=30)).extra(
            select={'ctime': "strftime('%%Y-%%m-%%d',web_issues.create_datetime)"}).values('ctime').annotate(ct=Count('id'))

        for item in result:
            data_dict[item['ctime']][1]=item['ct']
        print(data_dict)
        return JsonResponse({'status':True,'data':list(data_dict.values())})